<?php
/**
  * Use：
  * Author：kan.yang@starcor.cn
  * DateTime：18-2-1 下午2:51
  * Description：
*/
set_time_limit(0);error_reporting(0);
header('Content-Type:text/xml; charset=utf-8');
include_once dirname(dirname(dirname(dirname(__FILE__))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
//加载 xml转为数组的np库
\ns_core\m_load::load_old("nn_class/ftp/ftp.class.php");
\ns_core\m_load::load_np("np_http_curl.class.php");

class script_asset_data
{
    private $obj_dc = null;

    private $obj_ftp  = null;

    private $obj_curl = null;

    private $str_v2_dir = '';

    private $str_comm_url = '';

    private $str_callback_url = '';

    private $arr_sp_list = array();

    private $int_page_size = 50;

    public function __construct()
    {
        $this->obj_dc = m_config::get_dc();

        $this->str_v2_dir = dirname(dirname(dirname(dirname(__FILE__))));

        global $g_bk_web_url;
        $bk_web_url = $g_bk_web_url;
        unset($g_bk_web_url);
        $this->str_callback_url = trim(trim(trim($bk_web_url,'\\'),'/'));
        $this->str_callback_url.="/v2/ns_api/gdgd_xiaole/delivery/coship/notify1.php";

        $this->obj_curl = new np_http_curl_class();

        $this->str_comm_url = get_config_v2('g_ls_media_path');

        $this->_conn_ftp_server($this->str_comm_url);
    }

    //脚本入口
    public function init()
    {
        //参数1：CP ID；参数2：本次执行条数，默认50
        $this->_import_cdn($_SERVER['argv'][1],$_SERVER['argv'][2]);
    }

    //注入CDN主程序
    private function _import_cdn($str_cp_id,$int_size = 0)
    {
        //公共部分的SQL语句
        $str_comm_sql = "FROM `nns_ls_media_path_relation` WHERE " . "1=1 AND nns_state IN (0,2) AND nns_import_num < 5";
        if(isset($str_cp_id) && strlen($str_cp_id) > 0)
        {
            $str_comm_sql .= " AND nns_cp_id in ('" . implode("','",explode(",",$str_cp_id)) . "')";
        }
        //求总数
        $str_sql = "SELECT COUNT(1) total " . $str_comm_sql;
        if(isset($int_size) && is_numeric($int_size) && $int_size > 0)
        {
            $str_sql .= " LIMIT 0," . $int_size;
            if($int_size <= $this->int_page_size)
            {
                $this->int_page_size = $int_size;
            }
        }
        $arr_count = nl_db_get_one($str_sql,$this->obj_dc->db());
        if(!is_array($arr_count) || empty($arr_count) || $arr_count['total'] <= 0)
        {
            echo '查询待注入的片源为空'; return false;
        }
        else
        {
            $arr_count = $arr_count['total'];
        }
        //引入日志文件
        include_once dirname($this->str_v2_dir) . "/mgtv_v2/mgtv_init.php";
        include_once dirname($this->str_v2_dir) . "/mgtv_v2/models/queue_task_model.php";
        //引入 nl_c2_task 文件
        include_once dirname($this->str_v2_dir) . "/nn_logic/c2_task/c2_task.class.php";
        //引入 delivery_cdn.timer 文件
        include_once $this->str_v2_dir . "/ns_timer/cdn/delivery_cdn.timer.php";
        //分页注入
        $int_page_total = (int)(($arr_count + $this->int_page_size - 1) / $this->int_page_size);
        $int_page = 0; $arr_update_media_ids = array();
        echo "共计：" . $arr_count . "条记录；总页数：" . $int_page_total;
        while($int_page < $int_page_total)
        {
            //拼接SQL语句
            $str_sql = "SELECT nns_id,nns_cp_id,nns_new_url,nns_kbps " . $str_comm_sql  . " LIMIT " . ($int_page * $this->int_page_size) . "," . $this->int_page_size;
            $arr_media_list = nl_query_by_db($str_sql,$this->obj_dc->db());
            //验证有效性
            if(is_array($arr_media_list) && !empty($arr_media_list))
            {
                $arr_media_ids = array(); $arr_media_items = array();
                //验证TS是否已经在转码后的FTP内
                foreach($arr_media_list as $media)
                {
                    //$str_path = $this->str_comm_url . '/' . $media['nns_cp_id'] . '/' . $media['nns_new_url'];
                    $str_path = $this->str_comm_url . '/' . $media['nns_new_url'];
                    $arr_check_ret = $this->_check_file_exsist($str_path);
                    if($arr_check_ret['ret'] != 0)
                    {
                        continue;
                    }
                    $arr_media_ids[] = $media['nns_id'];
                    $arr_media_items[$media['nns_id']] = $media;
                    usleep(10000);
                }
                echo "第{$int_page}页存在片源路径：" . var_export($arr_media_ids,true);
                if(empty($arr_media_ids))
                {
                    $int_page ++; continue;
                }

                //验证 CDN/EPG点播队列 是否存在该片源
                $str_sql = "SELECT nns_id,nns_ref_id FROM `nns_mgtvbk_c2_task` WHERE nns_type = 'media' AND nns_ref_id IN ('" . implode("','",$arr_media_ids) . "')";
                $arr_task_list = nl_query_by_db($str_sql,$this->obj_dc->db());
                //从中心同步 -> CDN/EPG点播队列
                $arr_not_task_list = array();
                if(is_array($arr_task_list) && !empty($arr_task_list))
                {
                    //已经注入到CDN/EPG点播队列
                    $arr_task_list = array_column($arr_task_list,'nns_ref_id');
                    $arr_not_task_list = array_diff($arr_media_ids,$arr_task_list);
                }
                else
                {
                    if($arr_task_list === true)
                    {
                        $arr_not_task_list = $arr_media_ids;
                    }
                    $arr_task_list = array();
                }
                if(is_array($arr_not_task_list) && !empty($arr_not_task_list))
                {
                    //过滤出可以注入到CDN的片源ID
                    $str_sql = "SELECT nns_id,nns_org_id,nns_media_id FROM `nns_mgtvbk_op_queue` WHERE nns_type = 'media' AND nns_media_id IN ('" . implode("','",$arr_not_task_list) . "')";
                    $arr_op_queue_list = nl_query_by_db($str_sql,$this->obj_dc->db());
                    if(is_array($arr_op_queue_list) && !empty($arr_op_queue_list))
                    {
                        $queue_task_model = new queue_task_model(); $bool_queue_ret = true;
                        foreach($arr_op_queue_list as $queue)
                        {
                            $bool_queue_ret = $queue_task_model->c2_task_start_all($queue['nns_id'],$queue['nns_org_id']);
                            //下发成功的片源
                            if($bool_queue_ret)
                            {
                                $arr_task_list[] = $queue['nns_media_id'];
                            }
                            usleep(30000);
                        }
                        unset($queue_task_model);
                    }
                    unset($arr_op_queue_list);unset($arr_not_task_list);
                }
                //查询CDN/EPG点播队列任务ID
                $arr_sp_task_list = array();
                if(!empty($arr_task_list))
                {
                    $str_sql = "SELECT nns_id,nns_org_id,nns_ref_id FROM `nns_mgtvbk_c2_task` WHERE nns_type = 'media' AND nns_ref_id IN ('" . implode("','",$arr_task_list) . "')";
                    $arr_task_list = nl_query_by_db($str_sql,$this->obj_dc->db());
                    if(is_array($arr_task_list) && !empty($arr_task_list))
                    {
                        foreach($arr_task_list as $task)
                        {
                            //查询SP信息
                            if(!isset($this->arr_sp_list[$task['nns_org_id']]))
                            {
                                $this->_query_sp_info($task['nns_org_id']);
                            }
                            //如果注入CDN的地址为空，不执行下面的操作，循环下一个SP
                            if(!isset($this->arr_sp_list[$task['nns_org_id']]) || strlen($this->arr_sp_list[$task['nns_org_id']]) <= 0)
                            {
                                continue;
                            }
                            //删除已经注入过得影片内容
                            $bool_del_ret = $this->_delete_cdn_exists_asset($this->arr_sp_list[$task['nns_org_id']],$task['nns_ref_id'],$arr_media_items[$task['nns_ref_id']]['nns_kbps']);
                            //注入CDN
                            if($bool_del_ret)
                            {
                                if(isset($arr_sp_task_list[$task['nns_org_id']]))
                                {
                                    $arr_sp_task_list[$task['nns_org_id']]['nns_task_id'][] = $task['nns_id'];
                                    $arr_sp_task_list[$task['nns_org_id']]['nns_ref_id'][] = $task['nns_ref_id'];
                                }
                                else
                                {
                                    $arr_sp_task_list[$task['nns_org_id']] = array(
                                        'nns_task_id' => array($task['nns_id']),
                                        'nns_ref_id' => array($task['nns_ref_id']),
                                    );
                                }

                                $arr_update_media_ids[] = $task['nns_ref_id'];
                            }
                            usleep(30000);
                        }
                    }
                }

                echo "第{$int_page}页允许注入CDN片源：" . var_export($arr_sp_task_list,true);

                //注入CDN
                if(!empty($arr_sp_task_list))
                {
                    foreach($arr_sp_task_list as $k => $sp)
                    {
                        $result_task = nl_c2_task::query_by_condition_v2(
                            $this->obj_dc,array(
                                'nns_id'  => $sp['nns_task_id'],
                                'nns_org_id'=> $k
                            )
                        );
                        $timer = new delivery_cdn_timer(
                            m_config::return_child_path($this->str_v2_dir . "/ns_timer/cdn/delivery_cdn.timer.php",'timer'),
                            $k
                        );
                        $timer->run($result_task);
                        usleep(30000);
                    }
                }
                unset($arr_task_list); unset($arr_sp_task_list);
            }
            unset($arr_media_list); $int_page ++ ; usleep(50000);
        }
        //更新关系表中的状态

        echo "更新关系表中的状态-总记录数：" . count($arr_update_media_ids);

        if(!empty($arr_update_media_ids))
        {
            $arr_update_media_ids = array_chunk($arr_update_media_ids,20);
            foreach($arr_update_media_ids as $update)
            {
                $str_sql = "UPDATE nns_ls_media_path_relation SET nns_state = 3,nns_import_num = nns_import_num + 1 WHERE nns_id IN ('" . implode("','",$update) . "')";
                nl_execute_by_db($str_sql,$this->obj_dc->db());
            }
            unset($arr_update_media_ids);
        }
        unset($arr_update_media_ids);

        return true;
    }

    //验证TS文件是否存在
    private function _check_file_exsist($ftp_url)
    {
        $ftp_url = trim($ftp_url,'/');
        $arr_ftp_config = parse_url($ftp_url);
        $path_ftp = (isset($arr_ftp_config["path"]) && strlen($arr_ftp_config["path"]) > 0) ? $arr_ftp_config["path"] : '';

        $result = $this->obj_ftp->check_file_exsist($path_ftp);
        return $result;
    }

    //删除已经在CDN注入过得内容
    private function _delete_cdn_exists_asset($str_sp_cdn_url,$str_asset_id,$str_kbps)
    {
        $str_xml = '<?xml version="1.0" encoding="utf-8"?>';
        $str_xml.= '<DeleteContent
                        providerID="coship"
                        assetID="' . $str_asset_id . '"
                        contentType="VOD"
                        reasonCode="201"
                        volumeName="coship"
                        responseURL="' . $this->str_callback_url . '"
                   >';
        $str_xml.= '<Input
                        transferBitRate="' . $str_kbps . '"
                        codec="h264"
                        format ="ts"
                    />';
        $str_xml.= '</DeleteContent>';


        $arr_header = array(
            "Content-Type: text/plain; charset=utf-8",
        );

        $this->obj_curl->post($str_sp_cdn_url, $str_xml,$arr_header,60);
        $curl_info = $this->obj_curl->curl_getinfo();

        return $curl_info['http_code'] == '200';
    }

    //查询SP信息，获取CDN配置
    private function _query_sp_info($str_sp_id)
    {
        $str_sql = "SELECT * FROM nns_mgtvbk_sp WHERE nns_id = '" . $str_sp_id . "'";
        $arr_sp_info = nl_db_get_one($str_sql,$this->obj_dc->db());
        if(is_array($arr_sp_info) && !empty($arr_sp_info))
        {
            $str_sp_config = json_decode($arr_sp_info['nns_config']);
            $str_cdn_send_mode_url = is_object($str_sp_config) ? $str_sp_config->cdn_send_mode_url : $str_sp_config['cdn_send_mode_url'];
            if(!empty($str_cdn_send_mode_url))
            {
                $str_cdn_send_mode_url = substr($str_cdn_send_mode_url,0,strlen($str_cdn_send_mode_url) - strlen(strrchr($str_cdn_send_mode_url, '/')) + 1);
                $this->arr_sp_list[$str_sp_id] = $str_cdn_send_mode_url . 'DeleteContent';
            }
        }
        unset($arr_sp_info);
    }

    //链接FTP
    private function _conn_ftp_server($ftp_url)
    {
        $ftp_url = trim($ftp_url,'/');
        $arr_ftp_config = parse_url($ftp_url);
        $host_ftp = (isset($arr_ftp_config["host"]) && strlen($arr_ftp_config["host"]) > 0) ? $arr_ftp_config["host"] : '';
        $user_ftp = (isset($arr_ftp_config["user"]) && strlen($arr_ftp_config["user"]) > 0) ? $arr_ftp_config["user"] : '';
        $pass_ftp = (isset($arr_ftp_config["pass"]) && strlen($arr_ftp_config["pass"]) > 0) ? $arr_ftp_config["pass"] : '';
        $port_ftp = (isset($arr_ftp_config["port"]) && strlen($arr_ftp_config["port"]) > 0) ? $arr_ftp_config["port"] : 21;
        $this->obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp);
    }
}

$obj_script_asset_data = new script_asset_data();
$obj_script_asset_data->init();
